package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.MemberDao;
import com.itheima.dao.OrderDao;
import com.itheima.dao.OrderSettingDao;
import com.itheima.entiy.PageResult;
import com.itheima.entiy.QueryPageBean;
import com.itheima.entiy.Result;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import com.itheima.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 预约设置服务
 */
@Service(interfaceClass = OrderSettingService.class)
@Transactional
public class OrderSettingServiceImpl implements OrderSettingService {

    @Autowired
    private OrderSettingDao orderSettingDao;

    @Autowired
    private MemberDao memberDao;

    @Autowired
    private OrderDao orderDao;

    //批量导入预约设置
    @Override
    public void add(List<OrderSetting> list) {
        if (list != null && list.size() > 0){
            for (OrderSetting orderSetting : list) {
                //判断当前日期是否已经进行了预约设置
                long countByOrderDate = orderSettingDao.findCountByOrderDate(orderSetting.getOrderDate());
                if (countByOrderDate > 0){
                    //已经进行了预约设置 执行更新操作
                    orderSettingDao.editNumberByOrderDate(orderSetting);
                }else {
                    //没有进行预约设置  执行插入操作
                    orderSettingDao.add(orderSetting);
                }
            }
        }


    }

    //根据月份查询对应的预约设置数据
    @Override
    public List<Map> getOrderSettingByMonth(String date) {
        String begin = date + "-1";
        String end = date + "-31";
        Map<String, String> map = new HashMap<>();
        map.put("begin",begin);
        map.put("end",end);
        //调用DAO 根据日期范围查询预约设置数据
        List<OrderSetting> list = orderSettingDao.getOrderSettingByMonth(map);
        List<Map> result = new ArrayList<>();
        if (list != null && list.size() > 0){
            for (OrderSetting orderSetting : list) {
                Map<String ,Object> m = new HashMap<>();
                m.put("date",orderSetting.getOrderDate().getDate());//获取日期数字(几号)
                m.put("number",orderSetting.getNumber());
                m.put("reservations",orderSetting.getReservations());
                result.add(m);
            }
        }
        return result;
    }

    //根据日期设置对应的预约设置数据
    @Override
    public void editNumberByDate(OrderSetting orderSetting) {
        //根据日期查询是否已经进行了预约设置
        Date orderDate = orderSetting.getOrderDate();
        long count = orderSettingDao.findCountByOrderDate(orderDate);
        if (count > 0){
            //当前日期已经进行了预约设置  需要执行更新操作
            orderSettingDao.editNumberByOrderDate(orderSetting);
        }else {
            //当前日期没有进行了预约设置  需要执行插入操作
            orderSettingDao.add(orderSetting);
        }
    }

    //预约列表分页查询
    @Override
    public PageResult findOrdersPage(QueryPageBean queryPageBean) {
        //获取分页条件
        Integer currentPage = queryPageBean.getCurrentPage();//当前页
        Integer pageSize = queryPageBean.getPageSize();//每页显示条数
        String queryString = queryPageBean.getQueryString();//查询条件

        //完成分页
        PageHelper.startPage(currentPage,pageSize);
        //查询预约列表数据
        Page<Map<String,Object>> page = orderSettingDao.findOrdersPage(queryString);

        //修改日期格式
        for (Map<String, Object> map : page) {
            //获取日期
            Date orderDate = (Date) map.get("orderDate");
            //调整格式
            String date = new SimpleDateFormat("yyyy年MM月dd日").format(orderDate);
            //返回到封装
            map.put("orderDate",date);
        }

        //返回分页结果
        return new PageResult(page.getTotal(),page.getResult());
    }

    //取消预约
    @Override
    public String delete(Integer id) {
        //查询预约用户的手机号，用于回信
        String phone = orderSettingDao.findphoneByid(id);

        //执行取消预约操作
        orderSettingDao.delete(id);

        //通过预约id查询预约日期
        Date orderDate = orderSettingDao.findDateByid(id);
        //通过预约日期查询已预约人数
        OrderSetting orderSetting = orderSettingDao.findByOrderDate(orderDate);
        //修改已预约人数
        orderSetting.setReservations(orderSetting.getReservations() -1);//设置预约人数-1
        orderSettingDao.editNumberByOrderDate(orderSetting);

        return phone;
    }

    //电话新增预约
    @Override
    public Result phoneAdd(Integer setmealid, Map map) throws Exception {

        //1、查询用户指定日期是否可预约
        //获取预约日期
        String orderDate = (String) map.get("orderDate");
        OrderSetting orderSetting = orderSettingDao.findByOrderDate(DateUtils.parseString2Date(orderDate));
        if (orderSetting == null){
            //指定日期没有进行预约设置 无法完成预约
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }

        //2、查询预约人数是否已满
        int number = orderSetting.getNumber();//可预约人数
        int reservations = orderSetting.getReservations();//已预约人数
        if (reservations >= number){
            //已经约满 无法预约
            return new Result(false,MessageConstant.ORDER_FULL);
        }

        //3、检查用户是否重复预约
        String phoneNumber = (String) map.get("phoneNumber");//查询用户输入的手机号
        Member member = memberDao.findByTelephone(phoneNumber);
        if (member != null){
            //判断是否在重复预约
            Integer memberId = member.getId();//会员ID
            Date order_date = DateUtils.parseString2Date(orderDate);//预约日期
            Order order = new Order(memberId, order_date, setmealid);
            //根据条件进行查询
            List<Order> byCondition = orderDao.findByCondition(order);
            if (byCondition != null && byCondition.size() > 0){
                //说明用户在重复预约 无法完成再次预约
                return new Result(false,MessageConstant.HAS_ORDERED);
            }
        }else {
            //4 检查当前用户是否为会员 如果是会员则直接完成预约 如果不是会员则自动完成注册并进行预约
            member = new Member();
            member.setPhoneNumber(phoneNumber);
            member.setName((String) map.get("name"));
            member.setIdCard((String) map.get("idCard"));
            member.setSex((String) map.get("sex"));
            member.setBirthday(DateUtils.parseString2Date((String) map.get("birthday")));
            member.setRemark((String) map.get("remark"));
            member.setRegTime(new Date());
            memberDao.add(member);//自动完成会员注册
        }

        //5 预约成功 更新单日的已预约人数
        Order order = new Order();
        order.setMemberId(member.getId());//设置会员ID
        order.setOrderDate(DateUtils.parseString2Date(orderDate));//预约日期
        order.setOrderType((String) map.get("orderType"));//预约类型
        order.setOrderStatus(Order.ORDERSTATUS_NO);//到诊状态
        order.setSetmealId(setmealid);
        orderDao.add(order);

        orderSetting.setReservations(orderSetting.getReservations() +1);//设置预约人数+1
        orderSettingDao.editNumberByOrderDate(orderSetting);

        //6、返回预约信息
        return new Result(true,MessageConstant.ORDER_SUCCESS,order.getId());


    }

    //根据预约id查询预约日期和用户电话
    @Override
    public Map<String, Object> confirm(Integer id) {
        //查询表格获取预约日期和用户电话
        Map<String, Object> map = orderSettingDao.confirm(id);
        return map;
    }
}
